package com.mall.user.service.impl;

import com.mall.user.common.exception.BusinessException;
import com.mall.user.common.response.ResultCode;
import com.mall.user.model.dto.address.AddressAddRequest;
import com.mall.user.model.dto.address.AddressUpdateRequest;
import com.mall.user.model.entity.Address;
import com.mall.user.model.entity.User;
import com.mall.user.model.vo.AddressVO;
import com.mall.user.service.AddressService;
import com.mall.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 地址管理服务实现
 */
@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Resource
    private UserService userService;

    @Override
    @Transactional
    public String addAddress(Long userId, AddressAddRequest addressAddRequest) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (addressAddRequest == null) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址信息不能为空");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        // 创建新地址
        Address newAddress = new Address();
        BeanUtils.copyProperties(addressAddRequest, newAddress);
        newAddress.setId(UUID.randomUUID().toString());
        newAddress.setCreatedTime(LocalDateTime.now());
        newAddress.setUpdatedTime(LocalDateTime.now());

        // 获取用户现有地址列表
        List<Address> addresses = user.getAddresses();
        if (addresses == null) {
            addresses = new ArrayList<>();
        }

        // 如果设置为默认地址，取消其他地址的默认状态
        if (Boolean.TRUE.equals(newAddress.getIsDefault())) {
            addresses.forEach(addr -> addr.setIsDefault(false));
        }

        // 如果是第一个地址，自动设为默认
        if (addresses.isEmpty()) {
            newAddress.setIsDefault(true);
        }

        // 添加新地址
        addresses.add(newAddress);
        user.setAddresses(addresses);

        // 更新用户信息
        boolean result = userService.updateById(user);
        if (!result) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "添加地址失败");
        }

        log.info("用户 {} 添加地址成功，地址ID: {}", userId, newAddress.getId());
        return newAddress.getId();
    }

    @Override
    @Transactional
    public boolean updateAddress(Long userId, AddressUpdateRequest addressUpdateRequest) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (addressUpdateRequest == null || StringUtils.isBlank(addressUpdateRequest.getId())) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址信息不能为空");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        List<Address> addresses = user.getAddresses();
        if (addresses == null || addresses.isEmpty()) {
            throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
        }

        // 查找要更新的地址
        Address targetAddress = null;
        for (Address address : addresses) {
            if (addressUpdateRequest.getId().equals(address.getId())) {
                targetAddress = address;
                break;
            }
        }

        if (targetAddress == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
        }

        // 如果设置为默认地址，取消其他地址的默认状态
        if (Boolean.TRUE.equals(addressUpdateRequest.getIsDefault())) {
            addresses.forEach(addr -> {
                if (!addr.getId().equals(addressUpdateRequest.getId())) {
                    addr.setIsDefault(false);
                }
            });
        }

        // 更新地址信息
        BeanUtils.copyProperties(addressUpdateRequest, targetAddress);
        targetAddress.setUpdatedTime(LocalDateTime.now());

        // 更新用户信息
        boolean result = userService.updateById(user);
        if (result) {
            log.info("用户 {} 更新地址成功，地址ID: {}", userId, addressUpdateRequest.getId());
        }
        return result;
    }

    @Override
    @Transactional
    public boolean deleteAddress(Long userId, String addressId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (StringUtils.isBlank(addressId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址ID不能为空");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        List<Address> addresses = user.getAddresses();
        if (addresses == null || addresses.isEmpty()) {
            throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
        }

        // 查找并删除地址
        Address toDelete = null;
        for (Address address : addresses) {
            if (addressId.equals(address.getId())) {
                toDelete = address;
                break;
            }
        }

        if (toDelete == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
        }

        boolean wasDefault = Boolean.TRUE.equals(toDelete.getIsDefault());
        addresses.remove(toDelete);

        // 如果删除的是默认地址，且还有其他地址，将第一个地址设为默认
        if (wasDefault && !addresses.isEmpty()) {
            addresses.getFirst().setIsDefault(true);
        }

        // 更新用户信息
        boolean result = userService.updateById(user);
        if (result) {
            log.info("用户 {} 删除地址成功，地址ID: {}", userId, addressId);
        }
        return result;
    }

    @Override
    public List<AddressVO> getUserAddresses(Long userId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }

        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        List<Address> addresses = user.getAddresses();
        if (addresses == null) {
            return new ArrayList<>();
        }

        return getAddressVO(addresses);
    }

    @Override
    public AddressVO getAddressById(Long userId, String addressId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (StringUtils.isBlank(addressId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址ID不能为空");
        }

        log.info("查找地址 - userId: {}, addressId: {}", userId, addressId);

        User user = userService.getById(userId);
        if (user == null) {
            log.warn("用户不存在 - userId: {}", userId);
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        List<Address> addresses = user.getAddresses();
        if (addresses == null || addresses.isEmpty()) {
            log.warn("用户没有地址数据 - userId: {}", userId);
            throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
        }

        log.info("用户地址列表大小: {}", addresses.size());
        for (Address address : addresses) {
            log.info("地址ID: {}, 查找ID: {}, 匹配: {}", address.getId(), addressId, addressId.equals(address.getId()));
            if (addressId.equals(address.getId())) {
                log.info("找到匹配地址 - addressId: {}", addressId);
                return getAddressVO(address);
            }
        }

        log.warn("未找到匹配地址 - userId: {}, addressId: {}", userId, addressId);
        throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
    }

    @Override
    public AddressVO getDefaultAddress(Long userId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }

        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        List<Address> addresses = user.getAddresses();
        if (addresses == null || addresses.isEmpty()) {
            return null;
        }

        for (Address address : addresses) {
            if (Boolean.TRUE.equals(address.getIsDefault())) {
                return getAddressVO(address);
            }
        }

        // 如果没有默认地址，返回第一个地址
        return getAddressVO(addresses.getFirst());
    }

    @Override
    @Transactional
    public boolean setDefaultAddress(Long userId, String addressId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (StringUtils.isBlank(addressId)) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "地址ID不能为空");
        }

        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ResultCode.NOT_FOUND, "用户不存在");
        }

        List<Address> addresses = user.getAddresses();
        if (addresses == null || addresses.isEmpty()) {
            throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
        }

        // 查找目标地址
        boolean found = false;
        for (Address address : addresses) {
            if (addressId.equals(address.getId())) {
                address.setIsDefault(true);
                found = true;
            } else {
                address.setIsDefault(false);
            }
        }

        if (!found) {
            throw new BusinessException(ResultCode.NOT_FOUND, "地址不存在");
        }

        // 更新用户信息
        boolean result = userService.updateById(user);
        if (result) {
            log.info("用户 {} 设置默认地址成功，地址ID: {}", userId, addressId);
        }
        return result;
    }

    @Override
    public AddressVO getAddressVO(Address address) {
        if (address == null) {
            return null;
        }

        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(address, addressVO);
        
        // 拼接完整地址
        StringBuilder fullAddress = new StringBuilder();
        boolean hasContent = false;
        
        if (StringUtils.isNotBlank(address.getProvince())) {
            fullAddress.append(address.getProvince());
            hasContent = true;
        }
        if (StringUtils.isNotBlank(address.getCity())) {
            fullAddress.append(address.getCity());
            hasContent = true;
        }
        if (StringUtils.isNotBlank(address.getDistrict())) {
            fullAddress.append(address.getDistrict());
            hasContent = true;
        }
        if (StringUtils.isNotBlank(address.getStreet())) {
            fullAddress.append(address.getStreet());
            hasContent = true;
        }
        if (StringUtils.isNotBlank(address.getDetail())) {
            fullAddress.append(address.getDetail());
            hasContent = true;
        }
        
        // 如果所有地址字段都为空，设置为空字符串而不是返回null
        addressVO.setFullAddress(hasContent ? fullAddress.toString() : "");
        
        log.debug("为地址 {} 构建完整地址: {}", address.getId(), addressVO.getFullAddress());

        return addressVO;
    }

    @Override
    public List<AddressVO> getAddressVO(List<Address> addressList) {
        if (addressList == null || addressList.isEmpty()) {
            return new ArrayList<>();
        }

        return addressList.stream()
                .map(this::getAddressVO)
                .collect(Collectors.toList());
    }
}
